package com.hzncc.flowable_diboot.controller.contractmanage;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.diboot.core.util.S;
import com.diboot.core.vo.JsonResult;
import com.diboot.core.vo.Pagination;
import com.diboot.core.controller.BaseCrudRestController;
import com.diboot.iam.annotation.OperationCons;
import com.diboot.iam.annotation.BindPermission;
import com.diboot.iam.annotation.Log;
import com.hzncc.flowable_diboot.contract.entity.ContractAudit;
import com.hzncc.flowable_diboot.contract.service.ContractAuditService;
import com.hzncc.flowable_diboot.entity.invoicemanage.InvoiceRegister;
import com.hzncc.flowable_diboot.service.invoicemanage.InvoiceRegisterService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.hzncc.flowable_diboot.entity.contractmanage.ContractDocumentManagement;
import com.hzncc.flowable_diboot.service.contractmanage.ContractDocumentManagementService;
import com.hzncc.flowable_diboot.vo.contractmanage.ContractDocumentManagementDetailVO;
import com.hzncc.flowable_diboot.vo.contractmanage.ContractDocumentManagementListVO;
import com.hzncc.flowable_diboot.dto.contractmanage.ContractDocumentManagementDTO;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.List;

/**
* 合同文件管理 相关rest接口
* @author MyName
* @version 1.0
* @date 2024-12-30
* Copyright © MyCorp
*/
@Slf4j
@RequestMapping("/contract-manage/contract-document-management")
@BindPermission(name = "合同文件管理")
@RestController
public class ContractDocumentManagementController extends BaseCrudRestController<ContractDocumentManagement> {

    @Autowired
    private ContractDocumentManagementService contractDocumentManagementService;
    @Autowired
    private ContractAuditService contractAuditService;
    @Autowired
    private InvoiceRegisterService invoiceRegisterService;

    /**
    * 查询资源对象的列表VO记录
    * <p>
    * url请求参数示例: ?fieldA=abc&pageSize=20&pageIndex=1&orderBy=id
    * </p>
    * @return
    * @throws Exception
    */
    @Log(operation = OperationCons.LABEL_LIST)
    @BindPermission(name = OperationCons.LABEL_LIST, code = OperationCons.CODE_READ)
    @GetMapping()
    public JsonResult<List<ContractDocumentManagementListVO>> getListVOMapping(ContractDocumentManagementDTO queryDto, Pagination pagination) throws Exception {
        return super.getViewObjectList(queryDto, pagination, ContractDocumentManagementListVO.class);
    }

    /**
    * 根据id查询资源对象的详情VO
    * @param id ID
    * @return
    * @throws Exception
    */
    @Log(operation = OperationCons.LABEL_DETAIL)
    @BindPermission(name = OperationCons.LABEL_DETAIL, code = OperationCons.CODE_READ)
    @GetMapping("/{id}")
    public JsonResult<ContractDocumentManagementDetailVO> getDetailVOMapping(@PathVariable("id")String id) throws Exception {
        ContractDocumentManagementDetailVO detailVO = contractDocumentManagementService.getViewObject(id, ContractDocumentManagementDetailVO.class);
        return JsonResult.OK(detailVO);
    }

/**
    * 根据指定字段和值查询资源对象的详情VO
    * @param fieldName 字段名
    * @param fieldValue 字段值
    * @return
    * @throws Exception
    */
    @BindPermission(name = OperationCons.LABEL_DETAIL, code = OperationCons.CODE_READ)
    @GetMapping("/{fieldName}/{fieldValue}")
    public JsonResult<ContractDocumentManagementDetailVO> getDetailVOMapping(@PathVariable("fieldName") String fieldName, @PathVariable("fieldValue") String fieldValue) throws Exception {
        ContractDocumentManagementDetailVO detailVO = contractDocumentManagementService.getViewObject(fieldName, fieldValue, ContractDocumentManagementDetailVO.class);
        return JsonResult.OK(detailVO);
    }


    /**
    * 创建资源对象数据
    * @param contractDocumentManagement
    * @return JsonResult
    * @throws Exception
    */
    @Log(operation = OperationCons.LABEL_CREATE)
    @BindPermission(name = OperationCons.LABEL_CREATE, code = OperationCons.CODE_WRITE)
    @PostMapping()
    public JsonResult<Serializable> createModelMapping(@RequestBody ContractDocumentManagement contractDocumentManagement) throws Exception {
        contractDocumentManagementService.createEntity(contractDocumentManagement);
        // 更新合同回执状态
        if (S.equals(contractDocumentManagement.getDocType(), "0")){//合同正本
            UpdateWrapper<ContractAudit> updateWrapper = new UpdateWrapper<>();
            updateWrapper.lambda().set(ContractAudit::getContractOriginalRecoveryStatus, "1").eq(ContractAudit::getContractCode, contractDocumentManagement.getContractCode());
            contractAuditService.updateEntity(updateWrapper);
        }
        if (S.equals(contractDocumentManagement.getDocType(), "1")){//回执单
            UpdateWrapper<InvoiceRegister> updateWrapper = new UpdateWrapper<>();
            updateWrapper.lambda().set(InvoiceRegister::getReceipted, "1").set(InvoiceRegister::getReceiptDate, LocalDateTime.now()).eq(InvoiceRegister::getInvoiceNo, contractDocumentManagement.getInvoiceNo());
            invoiceRegisterService.updateEntity(updateWrapper);
        }
        return JsonResult.OK(contractDocumentManagement.getId());
    }

    /**
    * 根据id更新资源对象
    * @param contractDocumentManagement
    * @return JsonResult
    * @throws Exception
    */
    @Log(operation = OperationCons.LABEL_UPDATE)
    @BindPermission(name = OperationCons.LABEL_UPDATE, code = OperationCons.CODE_WRITE)
    @PutMapping("/{id}")
    public JsonResult<?> updateModelMapping(@PathVariable("id")String id, @RequestBody ContractDocumentManagement contractDocumentManagement) throws Exception {
        contractDocumentManagementService.updateEntity(contractDocumentManagement);
        return JsonResult.OK();
    }

    /**
    * 根据id删除资源对象
    * @param id
    * @return
    * @throws Exception
    */
    @Log(operation = OperationCons.LABEL_DELETE)
    @BindPermission(name = OperationCons.LABEL_DELETE, code = OperationCons.CODE_WRITE)
    @DeleteMapping("/{id}")
    public JsonResult<?> deleteModelMapping(@PathVariable("id") String id) throws Exception {
        boolean success = contractDocumentManagementService.deleteEntity(id);
        log.debug("删除数据 合同文件管理:{} {}", id, success? "成功":"失败");
        return JsonResult.OK();
    }

    /**
    * 根据ids集合删除资源对象
    * @param ids
    * @return
    * @throws Exception
    */
    @Log(operation = OperationCons.LABEL_BATCH_DELETE)
    @BindPermission(name = OperationCons.LABEL_DELETE, code = OperationCons.CODE_WRITE)
    @PostMapping("/batch-delete")
    public JsonResult<?> deleteEntityMapping(@RequestBody List<String> ids) throws Exception {
        boolean success = contractDocumentManagementService.deleteEntities(ids);
        log.debug("批量删除数据 合同文件管理:{} {}", ids, success? "成功":"失败");
        return JsonResult.OK();
    }

    /**
     * 批量上传文件
     * @param fileIds
     * @return
     * @throws Exception
     */
    @PostMapping("/batch-upload-files")
    public JsonResult<?> batchUploadFiles(@RequestParam String fileIds) throws Exception {
        if (fileIds == null || fileIds.isEmpty()){
            return JsonResult.FAIL_VALIDATION("文件为空");
        }
        try {
            contractDocumentManagementService.batchUploadFiles(fileIds);
        } catch (Exception e) {
            log.error("批量上传文件失败", e);
            return JsonResult.FAIL_INVALID_PARAM(e.getMessage());
        }
        return JsonResult.OK();
    }

    @GetMapping("/calculate-receipt-rate")
    public JsonResult<?> calculateReceiptRate() {
        // 计算合同正本回执率
        String result = contractDocumentManagementService.calculateReceiptRate();
        return JsonResult.OK(result);
    }

}